(function($){
	/** 
	 * 防止easyui panel移动越界
	 * @author wuhailong@rrjc.com
	 * @date 2016-01-10
	 */
	function onMovePatch (left, top) {
		//获取panel的宽高
		var panel = $(this).panel('panel');
		var pWidth = panel.outerWidth();
		var pHeight = panel.outerHeight();
		
		//判断panel的布局容器并获取容器的宽高
		var opts = $.data(this, 'panel').options;
		//非inline布局，则容器为浏览器窗口
		var container = opts.inline ? panel.parent() : $(window);
		var cWidth = container.width();
		var cHeight = container.height();

		//越界判断
		var _left = left < 0 ? 0 : left;
		var _top = top < 0 ? 0 : top;
		if (_left + pWidth > cWidth) {
			_left = cWidth - pWidth;
		}
		if (_top + pHeight > cHeight) {
			_top = cHeight - pHeight;
		}
		
		//仅在panel移出边界时调整位置，为避免死循环，不使用move方法
		if (_left != left || _top != top) {
			panel.css({left: _left, top: _top});
			var state = $.data(this, 'window');
			if (state){
				//更新panel位置，保证shadow同步
				state.options.left = _left;
				state.options.top = _top;
			}
		}
	}
	
	//移动越界补丁
	if ($.fn.pannel) {
		$.fn.pannel.defaults.onMove = onMovePatch;
	}
	if ($.fn.window) {
		$.fn.window.defaults.onMove = onMovePatch;
	}
	if ($.fn.dialog) {
		$.fn.dialog.defaults.onMove = onMovePatch;
	}
	
	/** 
	 * combobox增强补丁，支持autocomplete
	 * @author wuhailong@rrjc.com
	 * @date 2016-01-14
	 */
	if ($.fn.combobox) {
		function filter(combobox, query) {
			var state = combobox.data("combobox");
			var textField = state.options.textField;
			var data = state.data;
			for (var i = 0, len = data.length; i < len; i++) {
				if (data[i][textField].indexOf(query) == 0) {
					return true;
				}
			}
			return false;
		}
		
		$.extend($.fn.validatebox.defaults.rules, {
			_combobox: {
				validator: function(val,param){
					if (!val) {
						return true;
					} else {
						return filter($(param[0]), val);
					}
				},
				message: '没有匹配的结果'
			}
		});
		
		$.fn.combobox.methods.autocomplete = function(jq) {
			var id = +new Date;
			function nextId() {
				return 'combobox_' + (id++);
			}
			
			return jq.each(function(){
				var box = $(this);
				var boxOpts = box.combobox('options');
				//当且仅当可编辑且远程加载数据时启用
				if (!boxOpts.editable || boxOpts.mode != 'remote') {
					return;
				}
				
				//是否自动生成ID
				var id = box.attr('id');
				if (!id) {
					id = nextId();
					box.attr('id', id);
				}
				
				//校验匹配结果
				var comboOpts = box.combo('options');
				var ruleExp = "_combobox['#" + id + "']";
				var validType = comboOpts.validType;
				if (typeof validType == 'string') {
					validType = [validType, ruleExp];
				} else {
					if ($.isArray(validType)) {
						validType.push(ruleExp);
					} else {
						validType = ruleExp;
					}
				}
				
				//重置combo的validType，因为validatebox的options继承自combo的options
				comboOpts.validType = validType;
				var textbox = box.combo('textbox');
				textbox.data('validatebox').options.validType = validType;
				//TODO 完善combobox模糊筛选自动匹配的体验
//				var textField = boxOpts.textField;
//				var valField = boxOpts.valueField;
//				textbox.blur(function(){
//					var text = box.combobox('getText');
//					var val = box.combobox('getValue');
//					if (text == val && textField != valField) {
//						var data = box.combobox('getData');
//						if (text && data.length) {
//							//若用户未选择，自动选择第一条匹配结果
//							box.combobox('setValue', data[0][valField]);
//						} else {
//							//如果无匹配结果，重置value和text
//							box.combobox('setValue', '');
//							box.combobox('setText', text);
//						}
//					}
//				});
//				textbox.blur(function(){
//					var text = $(box.combobox('getText'));
//					var val = box.combobox('getValue');
//					if (text == val) {
//						var state = combobox.data("combobox");
//						var textField = state.options.textField;
//						var data = state.data;
//						for (var i = 0, len = data.length; i < len; i++) {
//							if (data[i][textField] == text) {
//								box.combobox('setValue', data)
//							}
//						}
//						return false;
//					}
//				});
				
				//自动调整下拉列表的高度
				var height = parseInt(comboOpts.panelHeight) || 200;
				box.combo('panel').css({
					height: 'auto',
					maxHeight: height + "px"
				});
				
				boxOpts._onLoadSuccess = boxOpts.onLoadSuccess;
				boxOpts.onLoadSuccess = comboboxOnLoadSuccess;
			});
		};
		
		function comboboxOnLoadSuccess(data){
			var opts = $(this).combobox("options");
			opts.mode = 'local';
			opts._onLoadSuccess.call(this, data);
			
//			if (opts.editable && opts.mode == 'remote') {
				//只远程查询一次
//				if (!opts._data && data.length) {
//					opts._data = data;
//					opts.loader = function(param, success, error) {
//						var _data = opts._data;
//						var q = param.q && $.trim(param.q);
//						if (!q) {
//							success(_data);
//						} else {
//							//筛选匹配结果（前缀匹配startsWith）
//							var data = [];
//							var textField = opts.textField;
//							for (var i = 0; i < _data.length; i++) {
//								if (_data[i][textField].indexOf(q) == 0) {
//									data.push(_data[i]);
//								}
//							}
//							success(data);
//						}
//					};
//				}
//			}
		}
	}
	
	/** 
	 * tabs增强补丁，支持右键快键菜单
	 * @author wuhailong@rrjc.com
	 * @date 2016-01-13
	 */
	if ($.fn.tabs) {
		$.fn.tabs.methods.enableContextMenu = function(jq) {
			return jq.each(function(){
				var state = $.data(this, 'tabs');
				state.options.onContextMenu = onContextMenu;
				if (!state.menu) {
					state.menu = createContextMenu().appendTo(this);
					state.menu.menu({
						onClick: onMenuClick
					});
				}
			});
		};
		$.fn.tabs.methods.disalbeContextMenu = function(jq) {
			return jq.each(function(){
				var state = $.data(this, 'tabs');
				state.options.onContextMenu = $.fn.tabs.defaults.onContextMenu;
				if (state.menu) {
					var mState = $.data(state.menu[0], 'menu');
					mState.tabs = null;
					state.menu.remove();
					state.menu = null;
				}
			});
		}
		
		function onContextMenu(e, title, index) {
			e.preventDefault();
			var tt = $(this);
			var mm = tt.data("tabs").menu;
			var tabs = tt.tabs('tabs');
			var opts = tabs[index].panel('options');
			//无href、无iframe禁用重新加载（需要在tab的options中配置iframe为true）
			var disableItems = [!opts.closable, tabs.length == 1, index == 0, index == tabs.length - 1, !opts.href && !opts.iframe];
			var itemEles = mm.children(".menu-item");
			for (var i = 0; i < disableItems.length; i++) {
				if (disableItems[i]) {
					mm.menu("disableItem", itemEles[i]);
				} else {
					mm.menu("enableItem", itemEles[i]);
				}
			}

			var state = mm.data('menu');
			state.tab = index;
			state.tabs = tt;
			mm.menu('show', {
				left: e.pageX,
				top: e.pageY
			});
		};
		
		function createContextMenu() {
			var html = '<div style="display:none;">' +
							'<div data-options="name:\'close\'">关闭标签页</div>' +
							'<div data-options="name:\'closeOthers\'">关闭其他标签页</div>' +
							'<div data-options="name:\'closeLefts\'">关闭左侧标签页</div>' +
							'<div data-options="name:\'closeRights\'">关闭右侧标签页</div>' +
							'<div class="menu-sep"></div>' +
							'<div data-options="name:\'refresh\',iconCls:\'icon-reload\'">重新加载</div>' +
						'</div>'
			return $(html);
		}
		
		function onMenuClick(item) {
			var state = $.data(this, 'menu');
			var index = state.tab;
			var tabs = state.tabs;
			switch(item.name) {
				case 'close': closeTabs(tabs, index, index + 1, 99); break;
				case 'closeOthers': closeTabs(tabs, 0, 99, index); break;
				case 'closeLefts': closeTabs(tabs, 0, index, 99); break;
				case 'closeRights': closeTabs(tabs, index + 1, 99, 99); break;
				case 'refresh':
					var tab = tabs.tabs('getTab', index);
					if (tab.panel('options').href) {
						tab.panel('refresh');
					} else {
						var iframe = tab.find('iframe:first');
						var src = iframe.attr("src");
						if (src) {
							iframe.attr("src", src);
						}
					}
			}
		}
		
		function closeTabs(jq, start, end, exclude) {
			var tabs = jq.tabs("tabs");
			var from = Math.max(0, start);
			var to = Math.min(tabs.length, end);
			var list = [];
			for (var i = from; i < to; i++) {
				if (i == exclude) {
					continue;
				}
				var opts = tabs[i].panel('options');
				if (opts.closable) {
					//因为tabs数组长度变动，故使用title
					list.push(opts.title);
				}
			}
			for (var i = 0; i < list.length; i++) {
				jq.tabs("close", list[i]);
			}
		}
	}
	
	/** 
	 * datagrid增强补丁，查询结果为空时显示友好信息
	 * @author wuhailong@rrjc.com
	 * @date 2016-01-21
	 */
	if ($.fn.datagrid) {
		$.fn.datagrid.defaults.onBeforeLoad = function(param) {
//			var opts = $(this).datagrid('options');
//			opts._onLoadSuccess = opts.onLoadSuccess || function(){};
//			opts.onLoadSuccess = datagridOnLoadSuccess;
		}
		
		function datagridOnLoadSuccess(data) {
			if (data.length || data.total || (data.rows && data.rows.length)) {
				var opts = $(this).datagrid('options');
				opts._onLoadSuccess.call(this, data);
				return;
			}
			$.messager.show({
                title:'提示',
                msg:'无符合条件的结果',
                showType:'fade',
                timeout: 1500,
                style:{
                    right:'',
                    bottom:''
                }
			});
		}
	}
	
	//export接口
	$.rrjc = $.rrjc || {};
//	$.rrjc.datagrid = function(target, dgOptions, cmdOptions) {
//		return new Datagrid(target, dgOptions, cmdOptions);
//	};
	//弹出窗口遮罩效果
	$.rrjc.loading = function(msg) {
		var html  = '<div id="rrjc_window_shadow" class="window-mask" style="z-index:9999;opacity:0.5;">';
			html += '<div class="datagrid-mask-msg" style="display:block;left:50%;margin-left:-80px;background-color:#ccc;">'
			html += msg + '</div></div>';
		$(document.body).append(html);
	};
	//移除窗口遮罩效果
	$.rrjc.loaded = function() {
		$("#rrjc_window_shadow").remove();
	};
	//批量校验easyui输入控件
	$.rrjc.validate = function(target) {
		if ($.fn.validatebox){
			var t = $(target);
			t.find('.validatebox-text:not(:disabled)').validatebox('validate');
			var invalidbox = t.find('.validatebox-invalid');
			invalidbox.filter(':not(:disabled):first').focus();
			return invalidbox.length == 0;
		}
		return true;
	};
	
	//合并字段值相同的行单元格
	$.rrjc.mergeCells = function(datagrid, field) {
		var $dg = $(datagrid);
		var rows = $dg.datagrid('getRows');
		var merges = [];
		var cur = rows.length > 0 ? rows[0]: null;
		var index = 0;
		var rowSpan = 1;
		for (var i = 1; i < rows.length; i++) {
			if (rows[i].catalog == cur.catalog) {
				rowSpan++;
			} else {
				if (rowSpan > 1) {
					merges.push({
						index: index,
						field: field,
						rowspan: rowSpan
					});
				}
				index = i;
				rowSpan = 1;
				cur = rows[i];
			}
		}
		if (rowSpan > 1) {
			merges.push({
				index: index,
				field: field,
				rowspan: rowSpan
			});
		}

		for (var i = 0; i < merges.length; i++) {
			$dg.datagrid('mergeCells', merges[i]);
		}
	};
	
	//构建一个easyui-linkbutton
	$.rrjc.linkbutton = function(name, icon, onclick) {
		var html = '<a href="javascript:;" class="easyui-linkbutton" plain="true"';
		if (icon) {
			html += ' icon="' + icon + '"';
		}	
		if (onclick) {
			html += ' onclick="' + onclick + '"';
		} else {
			html += ' disabled="true"';
		}
		html += '>' + name + '</a>';
		return html;
	};
	
	$.rrjc.renderLinkbutton = function(context) {
		if ($.fn.linkbutton) {
			$('.easyui-linkbutton', context).linkbutton();
		}
	};
})(jQuery);